﻿using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics;
using Dsl.Ped.Desktop.Commands;
using Dsl.Ped.Desktop.Modules.Editor;
using Dsl.Ped.Desktop.Modules.ErrorViewer;

namespace Dsl.Ped.Desktop 
{
    /// <summary>
    /// Bootstrapper of the DSLPed desktop application
    /// </summary>
    public class Bootstrapper {

        /// <summary>
        /// Gets or sets the container for MEF composition
        /// </summary>
        public CompositionContainer Container { get; set; }

        /// <summary>
        /// Run the bootstrapping process
        /// </summary>
        public void Run() {

            // Load all available add-ins to the container
            this.LoadAddIns2Container();

            // Register modules that will be injected to the application
            this.RegisterModules();

            this.RegisterCommands();
        }

        /// <summary>
        /// Load all available framework applications to the MEF container
        /// </summary>
        private void LoadAddIns2Container() {

            var catalog = new AggregateCatalog();

            catalog.Catalogs.Add(new DirectoryCatalog(ApplicationResources.Instance.AddInsDirectory));

            Container = new CompositionContainer(catalog);

            try
            {
                Container.ComposeParts(ApplicationResources.Instance);
                ApplicationResources.Instance.Container = Container;
            } 
            catch (Exception exc)
            {
                Debug.WriteLine("Error: " + exc);
            }
        }
        
        /// <summary>
        /// Register modules that are gonna be injected into the DSLPed desktop 
        /// applicatoin
        /// </summary>
        private void RegisterModules()
        {
            ApplicationResources.Instance.RegisterModule(new EditorModule());
            ApplicationResources.Instance.RegisterModule(new ErrorViewerModule());
        }

        /// <summary>
        /// Register <see cref="IApplicationCommand"/> instances. These will be integrated
        /// into DSLPed desktop applicatoin
        /// </summary>
        public void RegisterCommands()
        {
            var newFileCommand = new NewFileCommand();
            ApplicationResources.Instance.RegisteredApplicationCommand.Add(newFileCommand);

            var openFileCommand = new OpenFileCommand();
            ApplicationResources.Instance.RegisteredApplicationCommand.Add(openFileCommand);

            var saveFileCommand = new SaveFileCommand();
            ApplicationResources.Instance.RegisteredApplicationCommand.Add(saveFileCommand);

            var saveFileAsCommand = new SaveFileAsCommand();
            ApplicationResources.Instance.RegisteredApplicationCommand.Add(saveFileAsCommand);
        }
    }
}
